<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFromRef" :model="queryParams" inline label-width="68px">
        <el-form-item label="配置Key">
          <el-input v-model="queryParams.swiperKey" placeholder="" />
        </el-form-item>

        <el-form-item>
          <el-button class="filter-item" type="primary" @click="handleQuery">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <i-ep-refresh />
            重置
          </el-button>
          <el-button
            v-hasPerm="['sys:swiperConfig:add']"
            type="success"
            @click.stop="handleOpenDialog()"
          >
            <i-ep-plus />
            新增
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card class="table-container" shadow="never">
      <el-table v-loading="loading" :data="list" stripe style="width: 100%">
        <!-- <el-table-column label="ID" width="50" prop="id" min-width="50" /> -->
        <el-table-column label="配置Key" prop="swiperKey" width="300" />
        <el-table-column label="修改时间" prop="updateTime" width="180" />

        <el-table-column label="备注" prop="remark" width="300" />

        <el-table-column fixed="right" label="操作" width="160">
          <template #default="scope">
            <el-button
              v-hasPerm="['sys:swiperConfig:update']"
              link
              size="small"
              type="primary"
              @click.stop="handleOpenDialog(scope.row.id)"
            >
              <i-ep-edit />
              修改
            </el-button>
            <el-button
              v-hasPerm="['sys:swiperConfig:delete']"
              link
              size="small"
              type="danger"
              @click.stop="handleDelete(scope.row.id)"
            >
              <i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:limit="queryParams.pageSize"
        v-model:page="queryParams.pageNum"
        v-model:total="total"
        @pagination="handleQuery"
      />
    </el-card>

    <el-drawer v-model="dialog.visible" :title="dialog.title" size="80%" @close="handleCloseDialog">
      <el-form ref="addFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-alert
          v-if="formData.id !== ''"
          :closable="false"
          title="修改配置下，不支持修改配置Key."
          type="warning"
        />
        <el-alert
          v-if="formData.id !== ''"
          :closable="false"
          title="默认10个swiper，去掉序号值，即可删除."
          type="warning"
        />
        <br />
        <el-form-item label="配置Key" prop="swiperKey">
          <el-input v-model="formData.swiperKey" :readonly="formData.id !== ''" />
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="formData.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>

      <el-card class="table-container" shadow="never" title="swiper列表">
        <el-button class="filter-item" type="primary" @click="handleAddSwiper">
          <i-ep-search />
          添加swiper
        </el-button>
        <el-table :data="formData.swiperList" stripe style="width: 100%">
          <el-table-column label="序号" prop="index" width="80">
            <template #default="scope">
              <el-input v-model="scope.row.index" />
            </template>
          </el-table-column>
          <el-table-column label="图片URL" prop="faceUrl" width="300">
            <template #default="scope">
              <el-input v-model="scope.row.faceUrl" />
            </template>
          </el-table-column>
          <el-table-column label="跳转URL" prop="linkUrl" width="300">
            <template #default="scope">
              <el-input v-model="scope.row.linkUrl" />
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" width="300">
            <template #default="scope">
              <el-input v-model="scope.row.remark" />
            </template>
          </el-table-column>
          <el-table-column label="删除">
            <template #default="scope">
              <el-button type="danger" @click="handleDeleteSwiper(scope.row)">
                <i-ep-delete />
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
defineOptions({
  name: 'Config',
  inheritAttrs: false
})

import { ElForm, ElTable } from 'element-plus'
import { ref, onMounted } from 'vue'
import request from '@/utils/request'

const BASE_URL = '/api/yyplatform/admin/sys/config/swiper/'

const list = ref([])
const total = ref(0)
const loading = ref(false)

const addFormRef = ref(ElForm)
const formData = ref({
  id: null,
  swiperKey: '',
  swiperListJson: '',
  swiperList: [],
  remark: ''
})
const rules = ref({
  swiperKey: [{ required: true, message: '必填项不能为空', trigger: 'blur' }]
})

const queryFromRef = ref()
const dialog = ref({
  title: '',
  visible: false
})

const queryParams = ref({
  swiperKey: '',
  pageNum: 1,
  pageSize: 20
})

function handleCloseDialog() {
  dialog.value.visible = false
  dialog.value.title = '添加配置'
  formData.value = {
    id: '',
    swiperKey: '',
    swiperListJson: '',
    swiperList: [],
    remark: ''
  }
}

async function handleOpenDialog(id) {
  if (id) {
    let res = await request({
      url: `${BASE_URL}/get?id=${id}`,
      method: 'get'
    })
    formData.value = res
    dialog.value.visible = true
    dialog.value.title = '修改配置'
  } else {
    var arr = []
    for (var i = 0; i < 5; i++) {
      arr.push({
        index: 'idx_' + i,
        faceUrl: '',
        linkUrl: '',
        remark: ''
      })
    }

    formData.value = {
      id: '',
      swiperKey: '',
      swiperListJson: '',
      swiperList: arr,
      remark: ''
    }
    dialog.value.visible = true
    dialog.value.title = '添加配置'
  }
}

async function submitForm() {
  addFormRef.value.validate(async (isValid) => {
    if (isValid) {
      const id = formData.value.id
      if (id) {
        let obj = formData.value
        obj.swiperListJson = JSON.stringify(obj.swiperList)

        let updateRes = await request({
          url: `${BASE_URL}/update`,
          method: 'post',
          data: obj
        })
        ElMessage.success('修改成功')
        handleCloseDialog()
        await handleQuery()
      } else {
        let obj = formData.value
        obj.swiperListJson = JSON.stringify(obj.swiperList)

        let addRes = await request({
          url: `${BASE_URL}/save`,
          method: 'post',
          data: obj
        })
        ElMessage.success('添加成功')
        handleCloseDialog()
        await handleQuery()
      }
    }
  })
}

function handleDelete(id) {
  ElMessageBox.confirm('确认删除已选中的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request({
      url: `${BASE_URL}/delete`,
      method: 'post',
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      data: {
        id: id
      }
    }).then(async () => {
      await handleQuery()
    })
  })
}

async function handleResetQuery() {
  queryParams.value = {
    swiperKey: '',
    pageNum: 1,
    pageSize: 20
  }
  await handleQuery()
}

async function handleQuery() {
  console.log(queryParams.value, 'queryParams')

  loading.value = true

  let queryRes = await request({
    url: `${BASE_URL}/query`,
    method: 'get',
    params: {
      ...queryParams.value
    }
  })

  loading.value = false
  list.value = queryRes.content
  total.value = parseInt(queryRes.totalElements)
}

//  =============================================================================================================================
function handleAddSwiper() {
  formData.value.swiperList.push({
    index: '',
    faceUrl: '',
    linkUrl: '',
    remark: ''
  })
}

function handleDeleteSwiper(row) {
  formData.value.swiperList.splice(row, 1)
}

//  =============================================================================================================================

onMounted(async () => {
  await handleQuery()
})
</script>
